// pages/article-editor/index.js
import {baseUrl, getTagBgList, getTagList, publishBgArticle, publishJlArticle} from '../../api/index'
import {vModel} from '../../utils/v-model'
import {isEmptyField, checkPhone} from '../../utils/util'
import {uploadFiles} from '../../utils/upload-file.js'
import {getUserLocation} from '../../utils/getLocation'
import {getUserInfo} from '../../utils/getUserInfo'
import {shareApp} from '../../utils/shareApp'

const sourceType = [['camera'], ['album'], ['camera', 'album']]
const sizeType = [['compressed'], ['original'], ['compressed', 'original']]
Page({
  
  /**
   * 页面的初始数据
   */
  data: {
    articleType: '',
    tagOptions: [],
    form: {
      owner: '',
      owner_phone: '',
      user_duty: 0,
      sender_phone: '',
      receiver_phone: '',
      content: '',
      tag: '0', // 默认为0 全部
      position: '',
      position_x: '',
      position_y: '',
      images: []
    },
    tagSelectedID: 0,
    imageList: [],
    sourceTypeIndex: 2,
    sourceType: ['拍照', '相册', '拍照或相册'],
    
    sizeTypeIndex: 2,
    sizeType: ['压缩', '原图', '压缩或原图'],
    
    countIndex: 8,
    count: [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
    
  },
  // 根据帖子类型获取参数
  getFormParams (type) {
    let _form = this.data.form
    let baseParams = {
      title: _form.content,
      content: _form.content,
      tag: _form.tag,
      position: _form.position,
      position_x: _form.position_x,
      position_y: _form.position_y,
      images: _form.images
    }
    if (type === 'bgt') {
      return Object.assign({}, baseParams, {
        // owner: _form.owner,
        // user_duty: _form.user_duty,
        bg_goods_info: _form.owner,
        bg_phone: _form.owner_phone,
        bg_sender_name: _form.sender_phone,
        bg_geter_name: _form.receiver_phone,
      })
    } else {
      return baseParams
    }
  },
  
  /**
   * 事件绑定
   */
  // 输入内容
  bindIptChange (e) {
    vModel(this, e)
  },
  // switch
  bindSwitchChange (e) {
    vModel(this, Object.assign({}, e, {detail: Number(e.detail)}))
    console.log(e)
  },
  // 选择位置
  bindChooseLocation: function () {
    let _this = this
    // 获取位置信息
    // getUserLocation()
    wx.chooseLocation({
      success (res) {
        _this.setData({
          'form.position': res.address,
          'form.position_x': res.latitude,
          'form.position_y': res.longitude
        })
      },
    })
  },
  // 选择分类标签
  bindSelectTag (e) {
    vModel(this, e)
    console.log(this.data.form)
  },
  // 后退
  bindClickLeft () {
    wx.navigateBack({
      delta: 1
    })
  },
  // 打开草稿箱
  bindClickRight () {
    wx.navigateTo({
      url: '/pages/draft/index',
    })
  },
  // 移除图片
  bindRemoveImage (e) {
    let _this = this
    let _index = e.currentTarget.dataset.index
    let copyImagesList = _this.data.imageList.map(item => item)
    let copyFormImages = _this.data.form.images.map(item => item)
    wx.showModal({
      title: '提示',
      content: '确认删除该图片？',
      success ({confirm}) {
        if (confirm) {
          copyImagesList.splice(_index, 1)
          copyFormImages.splice(_index, 1)
          _this.setData({
            imageList: copyImagesList,
            'form.images': copyFormImages,
            countIndex: 8 - copyFormImages.length
          })
        }
      }
    })
  },
  // 选择图片并上传
  chooseImage () {
    const _this = this
    wx.chooseImage({
      sourceType: sourceType[this.data.sourceTypeIndex],
      sizeType: sizeType[this.data.sizeTypeIndex],
      count: _this.data.count[this.data.countIndex],
      success (res) {
        console.log(res)
        let _imageList = _this.data.imageList.concat(res.tempFilePaths)
        _this.setData({
          imageList: _imageList
        }, () => {
          uploadFiles(res.tempFilePaths).then(data => {
            let _images = _this.data.form.images.concat(data.map(item => item.info))
            _this.setData({
              'form.images': _images,
              countIndex: 8 - _images.length
            })
          })
          // _this.uploadImage(res.tempFilePaths)
        })
      }
    })
  },
  // 上传图片
  uploadImage (imgs) {
    let that = this
    // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
    var tempFilePaths = imgs
    //启动上传等待中...
    wx.showToast({
      title: '正在上传...',
      icon: 'loading',
      mask: true,
      duration: 600000
    })
    let uploadImgCount = 0
    let _uploadedImages = []
    // console.log(util.getClientSetting().domainName)
    for (let i = 0, h = tempFilePaths.length; i < h; i++) {
      wx.uploadFile({
        url: baseUrl + '/api/article/upload_img',
        filePath: tempFilePaths[i],
        name: 'images',
        formData: {
          'imgIndex': i
        },
        header: {
          'Content-Type': 'multipart/form-data',
          'token': wx.getStorageSync('auth_token'),
          'positionx': wx.getStorageSync('user_location_x'),
          'positiony': wx.getStorageSync('user_location_y'),
        },
        success (res) {
          uploadImgCount++
          let data = JSON.parse(res.data)
          if (data.status === 1) {
            _uploadedImages.push(data.info)
            that.setData({
              'form.images': _uploadedImages
            })
          } else {
            wx.showToast({
              title: data.info
            })
          }
          
          //如果是最后一张,则隐藏等待中
          if (uploadImgCount === tempFilePaths.length) {
            wx.hideToast()
          }
        },
        fail: function (res) {
          wx.hideToast()
          wx.showModal({
            title: '错误提示',
            content: '上传图片失败',
            showCancel: false,
            success (res) { }
          })
        }
      })
    }
  },
  checkFormField () {
    let _this = this
    let _form = this.data.form
    let _isBgt = this.data.articleType === 'bgt'
    if (_isBgt && isEmptyField(_form.owner)) {
      wx.showModal({
        title: '提示',
        content: '货主/信息部不能为空',
        showCancel: false,
        confirmText: 'OK'
      })
      return false
    }
    
    if (_isBgt && isEmptyField(_form.owner_phone)) {
      wx.showModal({
        title: '提示',
        content: '手机号不能为空',
        showCancel: false,
        confirmText: 'OK'
      })
      return false
    }
    if (_isBgt && !isEmptyField(_form.owner_phone) && !checkPhone(_form.owner_phone)) {
      wx.showModal({
        title: '提示',
        content: '手机号为11为数字',
        showCancel: false,
        confirmText: 'OK'
      })
      return false
    }
  
    if (_isBgt && !isEmptyField(_form.sender_phone) && !checkPhone(_form.sender_phone)) {
      wx.showModal({
        title: '提示',
        content: '发货人手机号格式不正确',
        showCancel: false,
        confirmText: 'OK'
      })
      return false
    }
  
    if (_isBgt && !isEmptyField(_form.receiver_phone) && !checkPhone(_form.receiver_phone)) {
      wx.showModal({
        title: '提示',
        content: '收货人手机号格式不正确',
        showCancel: false,
        confirmText: 'OK'
      })
      return false
    }
    // 不对曝光内容负责将不能发帖
    if (_isBgt && _form.user_duty < 1) {
      wx.showModal({
        title: '提示',
        content: '你需要同意勾选“本人对曝光内容负责”才能发帖哦',
        confirmText: '同意',
        success ({confirm}) {
          if (confirm) {
            _this.setData({
              'form.user_duty': 1
            })
          }
        }
      })
      return false
    }
    if (isEmptyField(_form.content)) {
      wx.showModal({
        title: '提示',
        content: '内容不能为空',
        showCancel: false,
        confirmText: 'OK'
      })
      return false
    }
    
    if (isEmptyField(_form.position)) {
      wx.showModal({
        title: '提示',
        content: '请选择位置',
        showCancel: false,
        confirmText: 'OK'
      })
      return false
    }
    return true
  },
  // 发布
  bindPublish () {
    // 发布类型
    let _this = this
    let _articleType = _this.data.articleType
    let publishFun = _articleType === 'bgt' ? publishBgArticle : publishJlArticle
    getUserInfo(true).then(res => {
      if (!this.checkFormField()) return
      wx.showLoading({
        title: '发布中...',
      })
      publishFun(_this.getFormParams(_articleType)).then(res => {
        console.log(res)
        wx.hideLoading()
        wx.showToast({
          title: '发布成功！'
        })
        wx.showModal({
          title: '提示',
          content: '发布成功，是否立即查看？',
          success ({confirm}) {
            _this.setData({
              form: {
                owner: '',
                owner_phone: '',
                user_duty: 1,
                sender_phone: '',
                receiver_phone: '',
                content: '',
                tag: '0', // 默认为0 全部
                position: '',
                position_x: '',
                position_y: '',
                images: []
              },
              tagSelectedID: 0,
              imageList: [],
              countIndex: 8
            })
            wx.removeStorage({
              key: 'prev_edit_' + _articleType
            })
            if (confirm) {
              wx.navigateTo({
                url: '/pages/article/index?id=' + res.data.id
              })
            }
          }
        })
      }).catch(err => {
        console.log(err)
        wx.showToast({
          icon: 'none',
          title: err.data.info
        })
      })
    })
  },
  // 存草稿
  bindSaveDraft () {
    let _data = this.data
    wx.setStorage({
      key: 'prev_edit_' + _data.articleType,
      data: Object.assign({}, _data.form, {images: [], tag: '0'}),
      success () {
        wx.showToast({
          title: '已保存',
        })
      }
    })
  },
  // 图片预览
  previewImage (e) {
    const current = e.target.dataset.src
    wx.previewImage({
      current,
      urls: this.data.imageList
    })
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let _this = this
    let _type = options.type
    let _handle = {
      bgt: getTagBgList,
      jlt: getTagList,
    }
    // 获取标签列表
    _handle[_type]().then(res => {
      _this.setData({
        tagOptions: res.data.info
      })
    })
    wx.getStorage({
      key: 'prev_edit_' + _type,
      success ({data}) {
        _this.setData({
          form: Object.assign({}, data, {tag: '0'})
        })
      },
    })
    _this.setData({
      articleType: _type
    })
  },
  
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return shareApp()
  }
})
